<template>
  <div class="table-all">
  <!-- 搜索区 -->
  <div class="app-container search-box">
    <SearchForm
      :form="searchData.form"
      :options="searchData.options"
      @searchUpdate="search"
      @resetSearchData="resetSearchData"
    ></SearchForm>
  </div>
  <!-- 按钮区 -->
  <div class="app-container table-box">
    <div class="table-main">
      <!-- 表格 -->
      <v-table
        title="救援队伍数据"
        v-if="tableMainHeight>0"
        :table-columns="tableColumns"
        :table-data="tableData"
        :loading="loading"
        :is-index="true"
        ref="table"
        :maxHeight="tableMainHeight">
        <template #topButtonList>
          <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
        </template>
        <template #type="scope">
          {{getDictValue(scope.row.type, typeOptions)}}
        </template>
        <template #teamLevel="scope">
          {{getDictValue(scope.row.teamLevel, teamLevelOptions)}}
        </template>
        <template #operation="scope">
          <a v-hasPermission="['riskRescueTeam:add']" class="table-btn-edit table-operation"
             @click="handleEdit(scope.row)">{{$t('table.edit')}}</a>
          <a v-hasPermission="['riskRescueTeam:add']" class="table-btn-view table-operation"
             @click="handleDetail(scope.row)">{{$t('table.view')}}</a>
          <a v-hasPermission="['riskRescueTeam:delete']" class="table-btn-delete table-operation"
             @click="singleDelete(scope.row)">{{$t('table.delete')}}</a>
        </template>
      </v-table>
    </div>
    <div class="table-page">
      <!-- 页码 -->
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="search"/>
    </div>
  </div>
  <!-- 详情 -->
  <detailDialog :dialog-visible="detailDialogShow"
                @success="editSuccess"
                @close="editClose"
                :openType="detailOpenType"
                :id="detailId"
                :title="detailTitle"
  ></detailDialog>
    <tableImportDialog
      ref="importDialog"
      :dialog-visible.sync="importDialog.isVisible"
      :title="importDialog.title"
      :template-list="importTemplateList"
      :uploadOptions="uploadOptions"
    />
  </div>
</template>

<script>
  import { riskRescueTeamPage,
    riskRescueTeamExport,
    riskRescueTeamDelete,
    riskRescueTeamTemplate,
    riskRescueTeamImport} from '@/api/risk/rescueTeam'
  import SearchForm from '@/components/searchForm/index'
  import ButtonForm from '@/components/ButtonForm/index'
  import VTable from '@/components/VTable/index'
  import Pagination from '@/components/Pagination/index'
  import detailDialog from './detail.vue'
  import tableImportDialog from '@/components/TableImportDialog/tableImportDialog'
  export default {
    components:{
      VTable,Pagination,detailDialog,SearchForm,ButtonForm,tableImportDialog
    },
    data(){
      return{
        importDialog:{
          isVisible: false,
          title: '导入救援队伍信息'
        },
        importTemplateList: [
          {
            label: '下载导入模板',
            url: '/risk/riskRescueTeam/template',
            downloadFileName: '救援队伍导入模板.xlsx',
            // clickFn: this.downloadTemplate, //选填项，点击下载按钮时触发，如果想自己手动实现下载，可在这里定义方法，否则使用默认的下载方法
          },
        ],
        uploadOptions: {
          accept: '.xlsx', //限制文件格式，多个用逗号隔开如：'.xlsx,.png'
          uploadTextTip: '请上传excel文件,以.xlsx为后缀',
          url: '/risk/riskRescueTeam/import',
          // uploadFn: this.handleUpload, //选填项，点击确认时触发上传，如果想自己手动实现上传，可在这里定义方法，否则使用默认的上传方法
          successFn: this.handleUploadSuccess, //选填项，上传成功后触发
        },
        tableColumns:[
          {
            prop: 'name',
            label: '救援队伍名称',
            minWidth: '150',
            slotname: 'name',
            options: {}
          },
          {
            prop: 'type',
            label: '救援队伍类型',
            minWidth: '150',
            slotname: 'type',
            options: {}
          },
          {
            prop: 'teamLevel',
            label: '级别',
            minWidth: '150',
            slotname: 'teamLevel',
            options: {}
          },
          {
            prop: 'areaCode',
            label: '行政区划',
            minWidth: '150',
            slotname: 'areaCode',
            options: {}
          },
          {
            prop: 'affiliatedUnit',
            label: '隶属单位',
            minWidth: '150',
            slotname: 'affiliatedUnit',
            options: {}
          },
          {
            prop: 'director',
            label: '负责人姓名',
            minWidth: '150',
            slotname: 'director',
            options: {}
          },
          {
            prop: 'directorPhone',
            label: '负责人电话',
            minWidth: '150',
            slotname: 'directorPhone',
            options: {}
          },
          {
            prop: 'dataSource',
            label: '数据来源单位',
            minWidth: '150',
            slotname: 'dataSource',
            options: {}
          },
          {
            prop: 'updateTime',
            label: '更新时间',
            minWidth: '150',
            slotname: 'updateTime',
            options: {}
          },
          {
            prop: 'operation',
            label: '操作',
            width: '200',
            align: 'center',
            slotname: 'operation',
            overflow: false,
            fixed: 'right'
          }
        ],
        tableData:[],
        selection: [],
        loading:false,
        total:1,
        pageNum:1,
        pageSize:10,
        detailOpenType:"add",
        detailDialogShow:false,
        detailId:"",
        detailTitle:"新增",
        dict:{},
        searchData:{
          form:{
            name:'',
            type:'',
            areaCode:'',
            provinceCode:"",
            cityCode:"",
            countyCode:"",
            updateTimeRange:[],
          },
          options:[
            {
              title:'救援队伍名称',
              key: "name",
              type: "text",
            },
            {
              title:'救援队伍类型',
              key: "type",
              type: "select",
              multiple:false,
              option: {
                data: this.typeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "行政区划",
              key: "areaCodeAll",
              type: "gdAreaSelect",
              changeFn: this.searchAreacodeHandle, //如需对区域数据做更多的处理，可在这里定义方法
            },
            {
              title:'更新时间',
              key: "updateTimeRange",
              type: "date-to-date",
            },
          ]
        },
        buttonList:[
          // {name:'新增',methods:'handleAdd',type:'primary'},
          // {name:'导入',methods:'handleImport'},
          // {name:'导出',methods:'handleExport'}
          {name:'新增',methods:'handleAdd',type:'primary',hasPremission:["riskRescueTeam:add"]},
          {name:'模版下载',methods:'downloadTemplate',type:'primary',hasPremission:["riskRescueTeam:template"]},
          {name:'批量导入',methods:'handleUpload',type:'primary', btnType:"upload", accept:".xlsx",hasPremission:["riskRescueTeam:import"]},
          {name:'导出数据',methods:'handleExport',type:'primary',hasPremission:["riskRescueTeam:export"]}
        ],
        tableMainHeight: 0,
        // 字典
        typeOptions:[],
        teamLevelOptions:[],
      }
    },
    watch: {
      // 字典
      'typeOptions':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t=>{
            if(t.key=='type'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
    },
    methods:{
      downloadTemplate(){
        let fileName = "救援队伍导入模板.xlsx"
        return riskRescueTeamTemplate('', fileName)
      },
      handleUpload(file){
        const formData = new FormData()
        console.log("file====>",file)
        formData.append('file', file)
        riskRescueTeamImport(formData)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success('导入成功')
            }
            if(res.code === 400){
              this.$message.warning(res.message)
            }
            if (res.code === 500) {
              this.$message.error(res.message)
            }
            this.search()
          })
          .finally(() => {
          })
      },
      handleDetail(row){
        this.detailId = row.id
        this.detailOpenType = "detail"
        this.detailTitle="详情"
        this.detailDialogShow = true
      },
      handleUploadSuccess(){
        this.search()
        this.importDialog.isVisible = false
      },
      getCheckBoxValue(value,option){
        if(!value){
          return
        }
        let temp = []
        let data = value.split(",")
        data.forEach(t=>{
          let item = option.find(x=> x.value == t)
          if(item != undefined){
            temp.push(item.label)
          }
        })
        return temp.join(",")
      },
      getDictValue(value,option){
        let item = option.find(t=> t.value == value)
        if(item!=undefined){
          return item.label
        }
        return value
      },
      editClose(){
        this.detailDialogShow = false
      },
      editSuccess(){
        this.search()
        this.detailDialogShow = false
      },
      search(){
        this.fetch({
          ...this.searchData.form,
        })
      },
      fetch(params={}){
        params.pageSize = this.pageSize
        params.pageNum = this.pageNum
        this.loading = true
        riskRescueTeamPage(params).then(async res=>{
          if(res.code==200){
            this.total = res.data.total
            let rows = res.data.rows
            for(let item of rows){
              item.areaCode = await this.$commonJs.areaCodeToName(item)
            }
            this.tableData = res.data.rows
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final=>{
          this.loading = false
        })
      },
      // 重置搜索条件
      resetSearchData(){
        this.searchData.form = {
          name:'',
          type:'',
          areaCodeAll:'',
          provinceCode:"",
          cityCode:"",
          countyCode:"",
          updateTime:'',
        }
      },
      searchAreacodeHandle(arr){
        console.log(arr)
        this.searchData.form.provinceCode=arr[0]
        this.searchData.form.cityCode=arr[1]
        this.searchData.form.countyCode=arr[2]
      },
      // 触发按钮区域按钮方法
      clickButton(methods, data){
        this[methods](data)
      },
      handleAdd(){
        this.detailOpenType = "add"
        this.detailTitle = "新增"
        this.detailDialogShow = true
      },
      handleEdit(row){
        this.detailId = row.id
        this.detailOpenType = "edit"
        this.detailTitle="编辑"
        this.detailDialogShow = true
      },
      handleExport(){
        let params = {
          ...this.searchData.form
        }
        riskRescueTeamExport(params,`救援队伍_${new Date().getTime()}.xlsx`);
      },
      handleImport(){
        this.importDialog.isVisible = true
      },
      closeDialog(){
        this.detailDialogShow = false
      },

      singleDelete(row){
        this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          this.loading = true
          riskRescueTeamDelete(row.id).then(res=>{
            if(res.code==200){
              this.$message({
                message: this.$t('tips.deleteSuccess'),
                type: 'success'
              })
              this.search()
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          }).finally(final=>{
            this.loading = false
          })
        })
      }
    },
    activated(){
      this.fetch()
    },
    created(){
      // 获取字典值
      this.typeOptions = []
      this.teamLevelOptions = []
      this.$commonJs.filterDataDict("riskRescueTeamType",this.typeOptions)
      this.$commonJs.filterDataDict("riskTeamLevel",this.teamLevelOptions)
    },
    mounted(){
      this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
    }
  }
</script>

<style lang="scss" scoped>
  .table-all {
    display: flex;
    flex-direction: column;
    height: 100%;

  .search-box {
    padding-bottom: 6px;
  }

  .table-box {
    padding-top: 10px;
    flex: 1;
    display: flex;
    flex-direction: column;

  .table-main {
    flex: 1;
    overflow: auto;
  }

  .table-page {
  // padding-top: 10 px;
  // padding-bottom: 10 px;
  }

  ::v-deep .pagination-container {
    text-align: right;
  }

  }
  }
</style>
